package middleware

import (
	"blog-backend/internal/utils"
	"blog-backend/pkg/auth"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.RespondError(c, http.StatusUnauthorized, "Authorization header required")
			c.Abort()
			return
		}

		tokenString := strings.Split(authHeader, "Bearer ")
		if len(tokenString) < 2 {
			utils.RespondError(c, http.StatusUnauthorized, "Invalid token format")
			c.Abort()
			return
		}

		claims, err := auth.ParseToken(tokenString[1])
		if err != nil {
			utils.RespondError(c, http.StatusUnauthorized, "Invalid token")
			c.Abort()
			return
		}

		c.Set("userID", claims.UserID)
		c.Next()
	}
}